package com.sunxy.bluetoothdemo

import android.bluetooth.BluetoothAdapter
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanResult
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.common.frame.kt.asAutoDisposable
import com.common.frame.utils.LogUtils
import com.common.frame.utils.ToastUtil
import com.common.frame.utils.TransformUtils
import com.sunxy.bluetoothdemo.bean.BlueDeviceBean
import com.sunxy.bluetoothdemo.bean.IBeaconClass
import io.reactivex.Single


/**
 *
 *
 * @author: sunxy11
 * @email: sunxy11@iflytek.com
 * @date: 2022/10/18
 */
class BlueToothActivity: AppCompatActivity() {

    private val blueAdapter by lazy { BluetoothAdapter.getDefaultAdapter() }
    private val itemAdapter by lazy { ItemAdapter() }
    private var isScanIng = false

    private val dataModule by lazy { DataModule(itemAdapter) }

    private val scanCallback by lazy { object: ScanCallback() {
        @RequiresApi(Build.VERSION_CODES.O)
        override fun onScanResult(callbackType: Int, result: ScanResult?) {
            super.onScanResult(callbackType, result)
            LogUtils.e("onScanResult: $callbackType  result: $result")
            result?.let {
                Single.just(it)
                    .map { scanResult ->
                        val bts = scanResult.scanRecord?.bytes
                        val device = scanResult.device
                        val rssi = scanResult.rssi
                        IBeaconClass.fromScanData(device, rssi, bts)?.let { fromScanData ->
                            BlueDeviceBean(fromScanData.beaconName,
                                    fromScanData.bluetoothAddress,
                                    fromScanData.txPower,
                                    fromScanData.major,
                                    fromScanData.minor,
                                    fromScanData.rssi,
                                    fromScanData.distance.toString()
                            )
                        } ?:  BlueDeviceBean()
                    }
                    .compose(TransformUtils.defaultSingleSchedulers())
                    .subscribe({ bean ->
                        upload(bean)
                    }, { e ->
                        e.printStackTrace()
                    })
                    .asAutoDisposable(lifecycle)

            }
        }
    } }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_blue_tooth)

        window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR

        findViewById<View>(R.id.startScan).setOnClickListener {
            startScan()
        }

        findViewById<View>(R.id.stopScan).setOnClickListener {
            stopScan()
        }

       val recyclerView = findViewById<RecyclerView>(R.id.recycle_view)
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.adapter = itemAdapter

        startScan()

        dataModule.start()
    }


    override fun onDestroy() {
        super.onDestroy()
        blueAdapter.bluetoothLeScanner?.stopScan(scanCallback)
    }

    private fun startScan() {
        if (isScanIng) {
            ToastUtil.showShortToast("当前正在扫描中...")
        } else {
            if (!blueAdapter.isEnabled) {
                blueAdapter.enable()
            }
            blueAdapter.bluetoothLeScanner?.startScan(scanCallback)
            ToastUtil.showShortToast("扫描设备中....")
            isScanIng = true
        }
    }

    private fun stopScan() {
        if (isScanIng) {
            blueAdapter.bluetoothLeScanner?.stopScan(scanCallback)
            isScanIng = false
        }
        ToastUtil.showShortToast("已经停止扫描了")
    }

    private fun upload(bean: BlueDeviceBean) {
        if (TextUtils.isEmpty(bean.bluetoothAddress)) {
            return
        }
        dataModule.addBean(bean)
    }

}